import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, Search } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import {
  addHistory,
  clearSuggestion,
  cleatHistory,
  getSuggestion,
  removeHistory,
} from '@/store/acitons/search'
import { RootState } from '@/types/store'
const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 2. 防抖处理
  const { run } = useDebounceFn(
    function (e) {
      // console.log('搜索内容', e)
      // 删除的时候 不能 传参e 因为 防抖 e 最后是存在的 但是 keyword 被删除了
      if (!keyword) return
      dispatch(getSuggestion(keyword))
    },
    { wait: 500 }
  )
  // 1. 绑定关键字
  const [keyword, setKeyword] = useState('')
  const onChange = (e: string) => {
    setKeyword(e)
    // 有关键字
    if (e) {
      setShowSuggestion(true)
      //发请求
      run(e)
    } else {
      //没有关键字
      setShowSuggestion(false)
      // 注意:这里为什么清空 推荐列表
      // 如果有关键字 那么会先显示之前的搜索的推荐列表 然后发请求在覆盖数据
      // 所以要清空推荐列表
      dispatch(clearSuggestion())
    }
  }
  // 组件销毁 只执行一次次
  // 3. 获取数据并渲染
  const { suggestion, histories } = useSelector(
    (state: RootState) => state.history
  )

  // 4.正则表达式 处理高亮
  function highLight(str: string) {
    return str.replace(new RegExp(keyword, 'gi'), (match) => {
      return `<span>${match}</span>`
    })
  }
  // 5. 处理显示推荐或者历史记录  默认不显示推荐 显示历史记录
  const [showSuggestion, setShowSuggestion] = useState(false)
  // 6.根据关键字搜索内容
  const onSearch = (key: string) => {
    // 1. 关键字存储到历史记录
    dispatch(addHistory(key))
    // 2. 跳转到搜索结果页面
    history.push(`/search/result?keyword=${key}`)
    // console.log(key)
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(keyword)}>
            搜索
          </span>
        }
      >
        <Search
          placeholder="请输入关键字搜索"
          value={keyword}
          onChange={onChange}
        />
      </NavBar>
      <div
        className="history"
        style={{
          display: showSuggestion ? 'none' : 'block',
        }}
      >
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={() => dispatch(cleatHistory())}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>
        {/* 历史记录 */}
        <div className="history-list">
          {histories.map((item, index) => (
            <span
              className="history-item"
              key={index}
              onClick={() => onSearch(item)}
            >
              <span className="text-overflow">{item}</span>
              <Icon
                type="iconbtn_essay_close"
                onclick={() => dispatch(removeHistory(item))}
              />
            </span>
          ))}
        </div>
      </div>
      {/* 推荐结果 */}
      <div
        className={classnames('search-result', showSuggestion ? 'show' : '')}
      >
        {suggestion.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => onSearch(item)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value text-overflow"
              dangerouslySetInnerHTML={{ __html: highLight(item) }}
            ></div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default SearchPage
